package com.yhy.common.feign.exception;

import com.yhy.common.core.exception.GlobalServletExceptionHandlerResolver;
import com.yhy.common.core.result.Result;
import com.yhy.common.core.result.ResultEnum;
import com.yhy.common.core.utils.WebUtils;
import com.yomahub.tlog.context.TLogContext;
import feign.Feign;
import feign.FeignException;
import feign.Request;
import feign.RetryableException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * @author Jax-li
 */
@Slf4j
@RestControllerAdvice
@ConditionalOnBean(GlobalServletExceptionHandlerResolver.class)
public class GlobalFeignExceptionHandlerResolver extends GlobalServletExceptionHandlerResolver {

    private static void error(Request request, Throwable e, String cause) {
        log.warn("♦♦♦ feign error cause:[{}], uri: [{}], traceId: [{}], ex=【{}】",
                cause, request.url(), TLogContext.getTraceId(), e.getLocalizedMessage(), e);
    }

    @ConditionalOnBean(Feign.class)
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({FeignException.class, RetryableException.class})
    public void feignException(HttpServletResponse response, FeignException ex) {
        Request request = ex.request();
        Result<String> result = Result.fail(ex);
        error(request, ex, result.getMessage());
        String path = request.url().replace("https://", "http://").replace("http://", "/");
        result.setPath(path);
        result.setMessage(ResultEnum.CLIENT_UNAVAILABLE.getMsg() + path);
        WebUtils.renderJson(response, result);
    }

}
